package com.atguigu.sh.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * SaleTicket
 * 题目：三个售票员卖出30张票
 * 多线程编程的及业绩套路+模板
 * 1. 在高内聚低耦合的前提下，线程     操作（对外暴露的调用方法）  资源类
 *
 * @author daixl
 * @date 2021/6/14
 */
public class SaleTicket {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        /**
        //匿名内部类
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        }, "A").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        }, "B").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        }, "C").start();
        */

        /**
         * 使用lambda表达式写法
         */
        new Thread(() -> {for (int i = 1; i <= 40; i++) ticket.saleTicket();}, "A").start();
        new Thread(() -> {for (int i = 1; i <= 40; i++) ticket.saleTicket();}, "B").start();
        new Thread(() -> {for (int i = 1; i <= 40; i++) ticket.saleTicket();}, "C").start();
//        new Thread(() -> {
//            //暂停一会儿线程
//            try { TimeUnit.SECONDS.sleep( 3 ); } catch (InterruptedException e) { e.printStackTrace(); }
//            ticket.saleTicket();
//        }, "A").start();
//        while (ticket.number == 30) {
//
//        }
//        System.out.println(Thread.currentThread().getName() + "\t 主线程结束");
    }
}

/**
 * 资源类
 */
class Ticket {

    private volatile int number = 30;
    private Lock lock = new ReentrantLock();

//    public void saleTicket(){
//        if (number > 0) {
//            System.out.println(Thread.currentThread().getName() + "\t卖出第：" + (number --) + "\t还剩下：" + number);
//        }
//    }

    public void saleTicket(){
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "\t卖出第：" + (number --) + "\t还剩下：" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
